<?php

namespace App\Models;

use App\Models\Traits\ScopeLikeTrait;
use App\Models\Traits\ScopeTrashedTrait;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;
    use ScopeLikeTrait;
    use ScopeTrashedTrait;

    const ROLE_STUDENT = 0;

    const ROLE_TEACHER = 1;

    const ROLE_ADMIN = 2;

    const ROLES = [self::ROLE_STUDENT => '学生', self::ROLE_TEACHER => '老师', self::ROLE_ADMIN => '管理员',];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'role',];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token',];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['email_verified_at' => 'datetime',];

    protected $appends = ['role_title'];

    protected $with = ['profile'];

    public function skills()
    {
        return $this->belongsToMany(Skill::class, 'user_skill')->using(UserSkill::class);
    }

    public function courses()
    {
        return $this->belongsToMany(Course::class, 'user_course')->using(UserCourse::class);
    }

    public function careers()
    {
        return $this->belongsToMany(Career::class, 'user_career')->using(UserCareer::class);
    }

    public function profile()
    {
        return $this->hasOne(Profile::class);
    }

    public function works()
    {
        return $this->belongsToMany(Work::class)->using(UserWork::class)->withPivot(['result','review'])->withTimestamps();
    }

    public function learnCourseCount()
    {
        return $this->courses()->sum('learn_count');
    }

    public function scopeRole($query, $role)
    {
        return $query->where('role', $role);
    }

    public function scopeRoles($query, $roles)
    {
        return $query->whereIn('role', $roles);
    }

    public function getRoleTitleAttribute()
    {
        return array_key_exists($this->role, self::ROLES) ? self::ROLES[$this->role] : '未分类角色';
    }

    public function getIsStudentAttribute()
    {
        return $this->role == self::ROLE_STUDENT;
    }

    public function getIsTeacherAttribute()
    {
        return $this->role == self::ROLE_TEACHER;
    }

    public function getIsAdminAttribute()
    {
        return $this->role == self::ROLE_ADMIN;
    }
}
